<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/12/16
 * Time: 15:20
 * @link http://www.lmterp.cn
 */
namespace app\command;

use app\common\model\Account;
use app\common\model\AccountPlatform;
use app\common\model\Orders;
use app\common\model\OrdersDetail;
use app\common\model\ProductStore;
use app\common\service\platform\AmazonService;
use app\common\service\product\PlatformService;
use think\console\input\Argument;
use think\console\input\Option;
use think\Db;
use think\facade\Log;

/**
 * 修复订单
 * Class RepairOrder
 * @package app\command
 */
class RepairOrder extends BaseCommand
{

    /**
     * 修复多少天之前的订单
     * @var string
     */
    protected $beforeDay;

    protected function configure()
    {
        // 指令配置
        $this->setName('repairorder')
            ->addArgument('action', Argument::REQUIRED, "需要修复的类型")
            ->addOption('day', null, Option::VALUE_REQUIRED, "修复多少天之前的订单，默认【15】天");
    }

    protected function handler()
    {
    	$action = $this->input->getArgument("action");
    	if(!method_exists($this, $action))
        {
            $this->output->writeln("【{$action}】指令错误");
            return;
        }
    	$day = $this->input->hasOption("day")
                ? $this->input->getOption("day")
                : 15;
    	$this->beforeDay = date('Y-m-d', strtotime("-{$day}day"));
        // 执行指令
    	$this->$action();
    }

    /**
     * 修复订单 sku 为内部sku
     * @date 2020/12/16
     * @author longli
     */
    protected function sku()
    {
        OrdersDetail::with(['order' => function($query)
        {
            $query->field(['order_id', 'warehouse_id', 'weight']);
        }])->where([
            ["create_time", "egt", $this->beforeDay],
            ['sku', 'eq', Db::raw('platform_sku')]
        ])->chunk($this->defChunk, function($details)
        {
            foreach($details as $detail)
            {
                $this->output->write(".");
                $sku = PlatformService::getInstance()->getSkuByPlatformSku($detail->sku);
                if(is_string($sku) && ($productStore = ProductStore::getStoreBySku($sku)))
                {
                    $detail->save([
                        'sku' => $sku,
                        'store_id' => $productStore->store_id,
                        'name_ch' => $productStore->product->name_ch,
                        'image_url' => !empty($productStore->image_url) ? $productStore->image_url : $productStore->product->image_url,
                        'declare_en' => $productStore->product->declare_en,
                        'declare_ch' => $productStore->product->declare_ch,
                        'declare_price' => $productStore->product->declare_price,
                        'declare_weight' => $productStore->weight,
                    ]);
                    $detail->order->getWeight();
                }
            }
            $this->output->writeln("");
        });
    }

    /**
     * 修复订单图片
     * @date 2020/12/16
     * @author longli
     */
    protected function image()
    {
        Log::info("开始修复订单图片问题");
        OrdersDetail::where([
            ["create_time", ">=", $this->beforeDay],
            ["image_url", "=", ""],
        ])->chunk($this->defChunk, function($details)
        {
            foreach($details as $detail)
            {
                $this->output->write(".");
                if(!($store = ProductStore::where("sku", $detail->sku)->field(["image_url"])->find())) continue;
                $detail->image_url = $store->image_url;
                $detail->save();
            }
           $this->output->writeln("");
        });
        Log::info("完成修复订单图片问题");
    }

    /**
     * 修复亚马逊订单产品线上 URL
     * @date 2020/12/16
     * @author longli
     */
    protected function amazonUrl()
    {
        Log::info("开始修复亚马逊订单商品链接问题");
        $amazon = null;
        OrdersDetail::alias(" d")
           ->join(Orders::getTable() . " o", "o.order_id=d.order_id")
           ->join(Account::getTable() . " a", "a.account_id=o.account_id")
           ->join(AccountPlatform::getTable() . " p", "p.platform_id=a.platform_id")
           ->field(["d.*", "a.site", "a.account_id"])
           ->where([
               ["p.code", "=", "AMZ"],
               ["d.create_time", ">=", $this->beforeDay],
               ["d.url", "=", ""],
               ["a.site", "neq", ""]
           ])->chunk($this->defChunk, function($details) use(& $amazon)
           {
               foreach($details as $detail)
               {
                   $site = explode(',', $detail['site'])[0];
                    if($amazon === null) $amazon = new AmazonService($detail['account_id']);
                   $detail->url = $amazon->fillUrl($detail['product_code'], $site);
                   $detail->save();
               }
           });
        Log::info("完成修复亚马逊订单商品链接问题");
    }
}